<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>购物车</title>
		<link rel="stylesheet" type="text/css" href="css/gouwuche.css" />
	</head>
	<body>
		<div id="app">
			<template v-if="list.length">
				<table>
					<thread>
						<tr>
							<th></th>
							<th>商品名称</th>
							<th>商品单价</th>
							<th>购买数量</th>
							<th>操作
								<button @click="addShop">
									添加商品
								</button>
							</th>
						</tr>
						<tr v-for="(item,index) in list">
							<td>{{index + 1}}</td>
							<td>{{item.name}}</td>
							<td>{{item.price}}</td>
							<td>
								{{item.count}}
							</td>
							<td>
								<button @click="handleReduce(index)" :disabled="item.count === 1">
									-
								</button>
								<button @click="handleAdd(index)">
									+
								</button>
								<button @click="handleRemove(index)">移除</button>
							</td>

						</tr>
					</thread>
				</table>
				<div>总价 : ¥ {{totalPrice}}</div>
			</template>
			<div v-else> 购物车为空</div>
			<input v-model="addName" />
		</div>

		<script src="js/vue.js"></script>
		<!-- <script src="js/gouwuche.js"></script> -->
	</body>
	<script>
		var app = new Vue({
			el: '#app',
			data: {
				addName: "xxx",
				list: [{
						id: 12,
						name: 'vivo 1',
						price: 5888,
						count: 1
					}, {
						id: 24,
						name: 'xiaomi 9',
						price: 2888,
						count: 1
					}, {
						id: 35,
						name: 'iphone 10',
						price: 7888,
						count: 1
					},

				]
			},
			methods: {
				handleReduce: function(index) {
					if (this.list[index].count === 1) {
						console.log("只有一件了");
						return;
					}
					this.list[index].count--;
				},
				handleAdd: function(index) {
					console.log("添加商品")
					this.list[index].count++;
				},
				handleRemove: function(index) {
					console.log("删除" + this.list[index].name + "商品");
					this.list.splice(index, 1);
				},
				addShop: function() {
					let shop = {
						id: Math.random(100),
						name: this.addName,
						price: Math.random() * 10000,
						count: 1
					}
					this.list.push(shop);

				}
			},
			computed: {
				totalPrice: function() {
					var total = 0;
					for (var i = 0; i < this.list.length; i++) {
						var item = this.list[i];
						total += item.price * item.count;
					}
					//return total.toString().replace(/\B(?=(\d{3})+$)/g, ',');
					return total

				}
			}
		})
	</script>
</html>
